<?php

if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * booking controller
 * @author Phuc Nguyen - 09/03/2015
 * http://www.facebook.com/phucthuong
 * email : nguyenvanphuc0626@gmail.com
*/
class Booking extends BACKEND_Controller {

	public function __construct() {
		parent::__construct();
		require_once(APPPATH . 'modules/backend/autoload.php');
		if($this->is_logged_in() == FALSE ) {
			$this->session->set_userdata('redirect_uri', current_url());
			redirect('auth');
		}else {
			$this->load->language('stats');
		}
                $this->load->language('booking');              
                $this->load->model('booking_model');
                
                $this->load->library('bookinglib');
                $this->booking = new bookinglib();
                
	}
        
        private function menuTop(){
            $this->load->model('stats_model');
            $user_info                          = $this->stats_model->get_user_info($this->stats_model->get_user_id());
            $this->view_data['role_by_group']   = $user_info['role_list'];
            $this->view_data['username']        = $user_info['username'];
            return $this->view_data;
        }
        
        private function direct(){
            $checkDirect = $_SERVER['HTTP_REFERER'];
            if(!isset($checkDirect)){
                redirect(base_url());
            }
        }
        
        public function paymentMethod(){
            $this->direct();//prevent direct
            $id                     =       $this->input->get('id',null);
            $cid                    =       $this->input->get('cid',null);
            $this->view_data['id']  =       $id;
            switch ($id){
                case '1':
                    //$this->load->view('auth/paymentMethod/unpaid', $this->view_data);
                    break;
                case '2':
                    $info                           = $this->booking_model->getInfoContactsByParams(array('key'=>'customerID','value'=>$cid));
                    $this->view_data['phone']       = implode(", ", json_decode($info->phone));
                    $this->view_data['address']     = $info->address;
                    $this->view_data['province']    = $info->province;
                    
                    $this->load->view('auth/paymentMethod/tickettohome', $this->view_data);break;
                case '3':
                    $this->load->view('auth/paymentMethod/banktransfer', $this->view_data);break;
                case '4':
                    $this->load->view('auth/paymentMethod/requestdebts', $this->view_data);break;
                case '5':
                    $this->load->view('auth/paymentMethod/office', $this->view_data);
                    break;
                default :
                    break;
            }
        }
        
        public function getInfoBank(){
            $this->direct();//prevent direct
            $result = $this->booking_model->getListBanks($this->input->get('id',null));
            $info   = array(
                'id'                =>  $result[0]->id,
                'bank_name'         =>  $result[0]->bank_name,
                'account_name'      =>  $result[0]->account_name,
                'account_number'    =>  $result[0]->account_number,
                'aff'               =>  $result[0]->aff
            );
            die(json_encode($info));
        }

        public function index() {		
		$this->view_data	= array();
		$this->view_data['flash_message_error']         = $this->session->flashdata('flash_message_error');
		$this->view_data['flash_message']		= $this->session->flashdata('flash_message');
		
		if($this->database_connect_status){
                        $this->menuTop();
                        $this->load->view('auth/booking/index', $this->view_data);
                } else {
                        $this->view_data['flash_message']	= $this->lang->line('database_connect_failed');
                        $this->load->view('templates/backend/error', $this->view_data);	
                }
	}
        
        public function checkPNR($params1,$params2){
            if($params1 == ""){
                die("Vui lòng nhập mã đặt chỗ");
            }
            if($params2 == 1){
                $pnr = $this->booking_model->find_by(array('booking_place_code'=>$params1,'booking_types'=>$params2));

                if($pnr){
                    die("Mã đặt chỗ ".$params1."(LOẠI VÉ MỚI) đã được tạo trong booking hold! Vui lòng vào chức năng <a href='/auth/searchBooking.html'>tìm kiếm booking</a> để bít thêm thông tin!");
                } else {
                    $this->load->model('bookhistory_model');
                    $pnr = $this->bookhistory_model->find_by(array('booking_place_code'=>$params1,'booking_types'=>$params2));
                    if($pnr){
                        die("Mã đặt chỗ ".$params1."(LOẠI VÉ MỚI) đã được thanh toán! Vui lòng vào chức năng <a href='/auth/searchBooking.html'>tìm kiếm booking</a> để bít thêm thông tin!");
                    }
                }
            }
        }

        public function add($params = null){
            $this->direct();//prevent direct
            
            if($this->input->server('REQUEST_METHOD')=='POST'){
                    $this->view_data["booking"]                                 = new stdClass();
                    $this->view_data["booking"]->booking_place_code             = strtoupper($this->input->post('booking_place_code'));
                    $this->view_data["booking"]->airline                        = strtoupper($this->input->post('airline'));
                    $this->view_data["booking"]->booking_types                  = $this->input->post('booking_types');
                    $this->view_data["booking"]->customerID                     = strtoupper($this->input->post('customerID'));
                    $this->view_data["booking"]->booking_customer_name          = preg_replace("/[\n\r]/","|",strtoupper(trim($this->input->post('customersName'))));
                    $this->view_data["booking"]->booking_child                  = ($this->input->post('child'))?trim($this->input->post('child')):'';
                    $this->view_data["booking"]->total_pax                      = $this->input->post('total_pax');
                    $this->view_data["booking"]->net_fare                       = $this->input->post('net_fare_fake');
                    $this->view_data["booking"]->sale_fare                      = $this->input->post('sale_fare_fake');
                    $this->view_data["booking"]->payment_method                 = '';//mac dinh cho NULL
                    $this->view_data["booking"]->note                           = $this->input->post('note');
                    $this->view_data["booking"]->advance                        = 0;//mac dinh cho = 0 => thanh toan voi hang
                    $this->view_data["booking"]->owner                          = $this->session->userdata['user_id'];
                    $this->view_data["booking"]->lastupdated                    = time();
                    $this->view_data["booking"]->createdTime                    = time();
                    
                    //check pnr
                    $this->checkPNR($this->view_data["booking"]->booking_place_code,$this->view_data["booking"]->booking_types);
                    /*
                     * booking
                     */
                    if($this->input->post('booking')){
                        //AUTO
                        $arr_booking                                                = explode("\n",$this->input->post('booking'));
                        $this->view_data["booking"]->booking                        = json_encode($arr_booking);
                    } else {
                        //MANUAL
                        $booking_info_u                                             = $this->input->post('booking-info');
                        $this->view_data["booking"]->booking                        = json_encode($booking_info_u);
                    }

                    $this->view_data["booking"]->agent_code                 = $this->session->userdata['agent_code'];
                    $params                                                 = $this->booking_model->create($this->view_data["booking"]);
                    $logAction                                              = $this->lang->line('add_booking_success').' Mã KH = '.$this->view_data["booking"]->customerID.' Code='.strtoupper($this->input->post('booking_place_code')).' Hãng='.strtoupper($this->input->post('airline'));
                    unset($this->view_data["booking"]);
                    
                    //statistic booking hold
                    $this->load->model('bookStatistic_model');
                    $statistic = array(
                        'owner'         => $this->session->userdata['user_id'],
                        'lastupdated'   => date("Y-m-d")
                    );

                    $query = $this->bookStatistic_model->updateStatisticBookHold($statistic);
                    if(!$query){
                        $this->view_data["statistic"]                   = new stdClass();
                        $this->view_data["statistic"]->booking_hold     = 1;
                        $this->view_data["statistic"]->owner            = $statistic['owner'];
                        $this->view_data["statistic"]->agent_code       = $this->session->userdata['agent_code'];
                        $this->view_data["statistic"]->lastupdated      = $statistic['lastupdated'];
                        $this->bookStatistic_model->create($this->view_data["statistic"]);
                    }

                    if($params){
                            $this->session->set_flashdata('flash_message', $this->lang->line('update_successful'));
                            $paramAdminLog  = array(
                                'userid'            => $this->session->userdata['user_id'],
                                'lastLogin'         => date('Y-m-d :H:i:s',time()),
                                'ip'                => $_SERVER['REMOTE_ADDR'],
                                'logAction'         => $logAction,
                                'agent_code'        => $this->session->userdata['agent_code']
                            );
                            $this->user_model->insertUserAdminLog($paramAdminLog);
                            die("1");
                    }

            } else {
                $this->menuTop();
                
                $this->view_data['customerID']                  =  $this->input->get('customerid');
                $this->load->view('auth/booking/add', $this->view_data);
            }
            
        }
        
        public function apiVN1B(){
            $params = array(
                'sdata'             =>  $this->input->post('sdata'),
                'sairlines'         =>  $this->input->post('sairlines')
            );
            
            if($this->input->post('sairlines') == "VJ"){
                $link = API_URL_VJ;//API_URL_VJ;
            } else {
                $link = BOOK232_API_URL;
            }
            
            $opts = array('http' =>
                array(
                    'method'  => 'GET',
                    'timeout' => 6
                )
            );
            $context            =       stream_context_create($opts);
            $result             =       file_get_contents($link.$params['sdata'].'&sairlines='.$params['sairlines'], false, $context);
            
            if($result){
                $_result        =       json_decode($result);
                 if(empty($_result->flight)){
                    die("");
                } else {
                    die($result);
                }
            } else {
                die("");
            }
        }
}